import React, { useCallback, useEffect, useRef, useState } from 'react';

// 轻量级拖拽组件（仿 merchant-end-111 的 Drager 用法）
// 受控：通过 props 控制 left/top/width/height；拖拽时通过 onChange 回传新的位置与尺寸
export default function Drager({
  width = 50,
  height = 50,
  left = 0,
  top = 0,
  style = {},
  boundary = true,
  boundaryWidth = 270,
  boundaryHeight = 480,
  onChange,
  onDragStart,
  onClick,
  children,
}) {
  const [dragging, setDragging] = useState(false);
  const startRef = useRef({ x: 0, y: 0, left, top });

  useEffect(() => {
    // 当外部更新位置时，重置起始位置
    startRef.current.left = left;
    startRef.current.top = top;
  }, [left, top]);

  const onMouseDown = useCallback((e) => {
    e.preventDefault();
    setDragging(true);
    startRef.current = { x: e.clientX, y: e.clientY, left, top };
    onDragStart && onDragStart();

    const onMouseMove = (ev) => {
      if (!dragging) return;
      const dx = ev.clientX - startRef.current.x;
      const dy = ev.clientY - startRef.current.y;
      let newLeft = startRef.current.left + dx;
      let newTop = startRef.current.top + dy;
      if (boundary) {
        newLeft = Math.max(0, Math.min(newLeft, boundaryWidth - width));
        newTop = Math.max(0, Math.min(newTop, boundaryHeight - height));
      }
      onChange && onChange({ left: Math.round(newLeft), top: Math.round(newTop), width, height });
    };

    const onMouseUp = () => {
      setDragging(false);
      window.removeEventListener('mousemove', onMouseMove);
      window.removeEventListener('mouseup', onMouseUp);
    };

    window.addEventListener('mousemove', onMouseMove);
    window.addEventListener('mouseup', onMouseUp);
  }, [boundary, boundaryHeight, boundaryWidth, dragging, height, left, onChange, onDragStart, top, width]);

  const wrapperStyle = {
    position: 'absolute',
    left,
    top,
    width,
    height,
    cursor: dragging ? 'grabbing' : 'grab',
    ...style,
  };

  return (
    <div style={wrapperStyle} onMouseDown={onMouseDown} onClick={onClick}>
      {children}
    </div>
  );
}